// 文件状态管理的自定义 Hook

import { useState, useCallback, useEffect } from 'react';
import { FileItem, FileStatus } from '../types/filesystem';

interface FileStatusInfo {
  status: FileStatus;
  timestamp: number;
  originalContent?: string;
}

interface UseFileStatusOptions {
  workspacePath?: string;
}

export const useFileStatus = (options: UseFileStatusOptions) => {
  const { workspacePath } = options;
  
  const [fileStatuses, setFileStatuses] = useState<Map<string, FileStatusInfo>>(new Map());
  const [modifiedFiles, setModifiedFiles] = useState<Set<string>>(new Set());

  // 获取文件状态
  const getFileStatus = useCallback((filePath: string): FileStatus => {
    const statusInfo = fileStatuses.get(filePath);
    return statusInfo?.status || FileStatus.Normal;
  }, [fileStatuses]);

  // 设置文件状态
  const setFileStatus = useCallback((filePath: string, status: FileStatus, originalContent?: string) => {
    setFileStatuses(prev => {
      const newMap = new Map(prev);
      newMap.set(filePath, {
        status,
        timestamp: Date.now(),
        originalContent,
      });
      return newMap;
    });

    // 更新修改文件列表
    if (status === FileStatus.Modified) {
      setModifiedFiles(prev => new Set(prev).add(filePath));
    } else {
      setModifiedFiles(prev => {
        const newSet = new Set(prev);
        newSet.delete(filePath);
        return newSet;
      });
    }
  }, []);

  // 标记文件为已修改
  const markFileAsModified = useCallback((filePath: string, originalContent?: string) => {
    setFileStatus(filePath, FileStatus.Modified, originalContent);
  }, [setFileStatus]);

  // 标记文件为新增
  const markFileAsAdded = useCallback((filePath: string) => {
    setFileStatus(filePath, FileStatus.Added);
  }, [setFileStatus]);

  // 标记文件为删除
  const markFileAsDeleted = useCallback((filePath: string) => {
    setFileStatus(filePath, FileStatus.Deleted);
  }, [setFileStatus]);

  // 标记文件为冲突
  const markFileAsConflicted = useCallback((filePath: string) => {
    setFileStatus(filePath, FileStatus.Conflicted);
  }, [setFileStatus]);

  // 清除文件状态
  const clearFileStatus = useCallback((filePath: string) => {
    setFileStatuses(prev => {
      const newMap = new Map(prev);
      newMap.delete(filePath);
      return newMap;
    });

    setModifiedFiles(prev => {
      const newSet = new Set(prev);
      newSet.delete(filePath);
      return newSet;
    });
  }, []);

  // 清除所有状态
  const clearAllStatuses = useCallback(() => {
    setFileStatuses(new Map());
    setModifiedFiles(new Set());
  }, []);

  // 获取所有修改的文件
  const getModifiedFiles = useCallback((): string[] => {
    return Array.from(modifiedFiles);
  }, [modifiedFiles]);

  // 获取特定状态的文件
  const getFilesByStatus = useCallback((status: FileStatus): string[] => {
    const files: string[] = [];
    fileStatuses.forEach((statusInfo, filePath) => {
      if (statusInfo.status === status) {
        files.push(filePath);
      }
    });
    return files;
  }, [fileStatuses]);

  // 检查文件是否有未保存的更改
  const hasUnsavedChanges = useCallback((filePath: string): boolean => {
    const status = getFileStatus(filePath);
    return status === FileStatus.Modified || status === FileStatus.Added;
  }, [getFileStatus]);

  // 获取状态统计
  const getStatusStats = useCallback(() => {
    const stats = {
      [FileStatus.Normal]: 0,
      [FileStatus.Modified]: 0,
      [FileStatus.Added]: 0,
      [FileStatus.Deleted]: 0,
      [FileStatus.Conflicted]: 0,
    };

    fileStatuses.forEach((statusInfo) => {
      stats[statusInfo.status]++;
    });

    return stats;
  }, [fileStatuses]);

  // 批量设置文件状态
  const batchSetFileStatus = useCallback((updates: Array<{ path: string; status: FileStatus; originalContent?: string }>) => {
    setFileStatuses(prev => {
      const newMap = new Map(prev);
      updates.forEach(({ path, status, originalContent }) => {
        newMap.set(path, {
          status,
          timestamp: Date.now(),
          originalContent,
        });
      });
      return newMap;
    });

    // 更新修改文件列表
    setModifiedFiles(prev => {
      const newSet = new Set(prev);
      updates.forEach(({ path, status }) => {
        if (status === FileStatus.Modified) {
          newSet.add(path);
        } else {
          newSet.delete(path);
        }
      });
      return newSet;
    });
  }, []);

  // 监听文件变化（模拟）
  useEffect(() => {
    if (!workspacePath) return;

    // 这里可以集成实际的文件监控逻辑
    // 例如使用 Tauri 的文件监控 API
    
    // 模拟一些文件状态变化
    const interval = setInterval(() => {
      // 这里可以检查文件的实际状态
      // 并更新状态映射
    }, 5000);

    return () => clearInterval(interval);
  }, [workspacePath]);

  // 保存文件状态到本地存储
  const saveStatusesToStorage = useCallback(() => {
    if (!workspacePath) return;

    const statusData = Array.from(fileStatuses.entries()).map(([path, info]) => ({
      path,
      status: info.status,
      timestamp: info.timestamp,
    }));

    const storageKey = `file-statuses-${workspacePath.replace(/[^a-zA-Z0-9]/g, '_')}`;
    localStorage.setItem(storageKey, JSON.stringify(statusData));
  }, [workspacePath, fileStatuses]);

  // 从本地存储加载文件状态
  const loadStatusesFromStorage = useCallback(() => {
    if (!workspacePath) return;

    const storageKey = `file-statuses-${workspacePath.replace(/[^a-zA-Z0-9]/g, '_')}`;
    const savedData = localStorage.getItem(storageKey);

    if (savedData) {
      try {
        const statusData = JSON.parse(savedData);
        const newMap = new Map<string, FileStatusInfo>();
        const newModifiedSet = new Set<string>();

        statusData.forEach((item: any) => {
          newMap.set(item.path, {
            status: item.status,
            timestamp: item.timestamp,
          });

          if (item.status === FileStatus.Modified) {
            newModifiedSet.add(item.path);
          }
        });

        setFileStatuses(newMap);
        setModifiedFiles(newModifiedSet);
      } catch (error) {
        console.error('Failed to load file statuses from storage:', error);
      }
    }
  }, [workspacePath]);

  // 自动保存状态
  useEffect(() => {
    const timeoutId = setTimeout(() => {
      saveStatusesToStorage();
    }, 1000);

    return () => clearTimeout(timeoutId);
  }, [fileStatuses, saveStatusesToStorage]);

  // 加载初始状态
  useEffect(() => {
    loadStatusesFromStorage();
  }, [loadStatusesFromStorage]);

  return {
    // 状态查询
    getFileStatus,
    hasUnsavedChanges,
    getModifiedFiles,
    getFilesByStatus,
    getStatusStats,
    
    // 状态设置
    setFileStatus,
    markFileAsModified,
    markFileAsAdded,
    markFileAsDeleted,
    markFileAsConflicted,
    clearFileStatus,
    clearAllStatuses,
    batchSetFileStatus,
    
    // 存储管理
    saveStatusesToStorage,
    loadStatusesFromStorage,
    
    // 状态数据
    fileStatuses,
    modifiedFiles,
  };
};
